
var mongodb 	= require('mongodb');



var parse_token = function (token) {
	var data = token.split(',');

	if (data.length === 4) {
		return {
			e:	data[0],
			x:	parseInt(data[1], 36),
			y:	parseInt(data[2], 36),
			t:	parseInt(data[3], 36)
		}
	}

	return false;
}


var generate_key = function(parsed_token) {
	return parsed_token.x + (parsed_token.y << 9);
}



exports.collect = function (req, res, client, request) {

	var clctr_events		= new mongodb.Collection(client, 'clctr_' + request.page.id + '_events')
	,	clctr_move			= new mongodb.Collection(client, 'clctr_' + request.page.id + '_moves')
	,	clctr_sessions		= new mongodb.Collection(client, 'clctr_' + request.page.id + '_sessions')
	,	session				= request.session
	;

	if (request.page.id && request.session.user_id  && req.query.sn) {

		var tokens		= (req.query.d ? req.query.d.split('|') : [])
		,	start		= new Date().getTime()
		,	session_id	= new mongodb.BSONPure.ObjectID(req.query.sn.toString(10).substr(0,12))
		,	events		= []
		,	moves		= []
		;

		console.log("Received the following " + tokens.length + " tokens:");
		console.log(tokens);

		for (var i = 0, len = tokens.length; i < len; i++) {

			var token		= parse_token(tokens[i])
			,	key			= generate_key(token)
			;

			events.push(token);

			if (token.e === 'm') {
				if (moves[key]) {
					moves[key]['$inc'].c++;
				} else {
					moves[key] = {$inc: {c: 1}};
				}
			}
		};

		clctr_events.insert(events, {safe: true});

		for (key in moves) {
			if (moves.hasOwnProperty(key)) {
				clctr_move.update({"_id": parseInt(key)}, moves[key], {upsert: true, safe: true});
			}
		}

		if (session.events) {
			clctr_sessions.update({"_id": session_id}, {$pushAll: {events:events}}, {save: true});
		} else {
			session.events = events;
			session['_id'] = session_id;
			clctr_sessions.insert(session, {save: true});
		}
	} else {
		console.log("Collector request failed because of missing query parameters");
	}

	res.writeHead(200, {'Content-Type': 'image/gif'});
	res.end('\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\xf0\x01\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x0a\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b', 'binary');

};





